package com.mobilezu.mobile.android.mobile4s.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class CommonHelper {

	/**
	 * 记录操作日志
	 * 
	 * @param content
	 *            日志内容
	 */
	public static void log(String content) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String sdDir = Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ File.separator
					+ "sms/check"
					+ File.separator + "log/user_operation";
			File file = new File(sdDir);
			if (!file.isDirectory()) {
				boolean mkOk = file.mkdirs();
				if (!mkOk) {
					return;
				}
			}
			File sdCardDir = new File(sdDir);
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String fileName = sdf.format(date) + ".txt";
			File saveFile = new File(sdCardDir, fileName);
			FileOutputStream outStream = null;
			try {
				outStream = new FileOutputStream(saveFile, true);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return;
			}
			content = "\r\n" + CommonHelper.getCurrentTime()
					+ "------------------\r\n" + content + "\r\n";
			try {
				outStream.write(content.getBytes());

			} catch (IOException e) {
				CommonHelper.log(CommonHelper.class.getName(),
						"log：" + e.getMessage());
				return;
			} finally {
				try {
					outStream.close();
				} catch (IOException e) {
					CommonHelper.log(CommonHelper.class.getName(),
							"log：" + e.getMessage());
				}
			}
		}
	}

	/**
	 * 记录系统日志
	 * 
	 * @param modelName
	 *            模块名称
	 * @param content
	 *            日志内容
	 */
	public static void log(String modelName, String content) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String sdDir = Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ File.separator
					+ "sms/check"
					+ File.separator + "log/system_operation";
			File file = new File(sdDir);
			if (!file.isDirectory()) {
				boolean mkOk = file.mkdirs();
				if (!mkOk) {
					return;
				}
			}
			File sdCardDir = new File(sdDir);
			// 获取SDCard目录,2.2的时候为:/mnt/sdcard
			// 2.1的时候为：/sdcard，
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String fileName = sdf.format(date) + ".txt";
			File saveFile = new File(sdCardDir, fileName);
			FileOutputStream outStream = null;
			try {
				outStream = new FileOutputStream(saveFile, true);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return;
			}
			content = "\r\n" + CommonHelper.getCurrentTime()
					+ "------------------\r\n" + content + "\r\n";
			try {
				outStream.write(content.getBytes());

			} catch (IOException e) {
				CommonHelper.log(CommonHelper.class.getName(),
						"log：" + e.getMessage());
				return;
			} finally {
				try {
					outStream.close();
				} catch (IOException e) {
					CommonHelper.log(CommonHelper.class.getName(),
							"log：" + e.getMessage());
				}
			}
		}
	}

	/**
	 * 
	 * @return 当前系统时间：格式为yyyy-MM-dd HH:mm:ss
	 */
	public static String getCurrentTime() {
		SimpleDateFormat dataFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		return dataFormat.format(new Date());
	}

	/**
	 * 写入图片到sdcard
	 * 
	 * @param b
	 * @param destDirStr
	 * @param file
	 */
	public static void writeFile(byte[] b, String destDirStr, String file) {
		// 获取扩展SD卡设备状态
		String sDStateString = android.os.Environment.getExternalStorageState();
		File myFile = null;
		// 拥有可读可写权限
		if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
			try {
				// 获取扩展存储设备的文件目录
				File SDFile = android.os.Environment
						.getExternalStorageDirectory();
				File destDir = new File(SDFile.getAbsolutePath()
						+ File.separator + destDirStr);
				if (!destDir.exists())
					destDir.mkdirs();
				// 打开文件
				myFile = new File(destDir + File.separator + file);
				// 判断是否存在,不存在则创建
				if (!myFile.exists()) {
					myFile.createNewFile();
				} else {
					myFile.delete();
				}
				// 写数据
				FileOutputStream outputStream = new FileOutputStream(myFile);
				outputStream.write(b);
				outputStream.flush();
				outputStream.close();
				outputStream = null;
			} catch (Exception e) {
				CommonHelper.log(CommonHelper.class.getName() + " writeFile:"
						+ e.getMessage());
			} finally {
				b = null;
			}
		}
	}

	/**
	 * 直接将字符串文本写入到文件中
	 * 
	 * @param content
	 *            文本文件
	 * @param destDirStr
	 *            目标目录
	 * @param file
	 */
	public static void writeFile(String content, String destDirStr, String file) {
		// 获取扩展SD卡设备状态
		String sDStateString = android.os.Environment.getExternalStorageState();
		File myFile = null;
		BufferedReader bufferedReader = null;
		BufferedWriter bufferedWriter = null;

		// 拥有可读可写权限
		if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
			try {
				// 获取扩展存储设备的文件目录
				File SDFile = android.os.Environment
						.getExternalStorageDirectory();
				File destDir = new File(SDFile.getAbsolutePath()
						+ File.separator + destDirStr);
				if (!destDir.exists())
					destDir.mkdirs();
				// 打开文件
				myFile = new File(destDir + File.separator + file);
				// 判断是否存在,不存在则创建
				if (!myFile.exists()) {
					myFile.createNewFile();
				} else {
					myFile.delete();
				}
				bufferedReader = new BufferedReader(new StringReader(content));
				java.io.FileOutputStream writerStream = new java.io.FileOutputStream(
						myFile);
				bufferedWriter = new BufferedWriter(
						new java.io.OutputStreamWriter(writerStream, "utf-8"));
				char buf[] = new char[1024]; // 字符缓冲区
				int len;
				while ((len = bufferedReader.read(buf)) != -1) {
					bufferedWriter.write(buf, 0, len);
				}
				bufferedWriter.flush();
				bufferedReader.close();
				bufferedWriter.close();
				bufferedReader = null;
				bufferedWriter = null;
				// 写数据
			} catch (Exception e) {
				CommonHelper.log(CommonHelper.class.getName() + " writeFile:"
						+ e.getMessage());
			}
		}
	}

	/**
	 * 写入图片到sdcard
	 * 
	 * @param b
	 * @param destDirStr
	 * @param file
	 */
	public static void writeFileAppend(byte[] b, String fileFullPath,
			boolean isAppend) {
		// 获取扩展SD卡设备状态
		String sDStateString = android.os.Environment.getExternalStorageState();
		File myFile = null;
		// 拥有可读可写权限
		if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
			try {
				// 获取扩展存储设备的文件目录
				String fileDir = fileFullPath.substring(0,
						fileFullPath.lastIndexOf("/") + 1);
				File dir = new File(fileDir);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				// 打开文件
				myFile = new File(fileFullPath);
				// 判断是否存在,不存在则创建
				if (!myFile.exists()) {
					myFile.createNewFile();
				}
				// 写数据
				FileOutputStream outputStream = new FileOutputStream(myFile,
						isAppend);
				outputStream.write(b);
				outputStream.flush();
				outputStream.close();
			} catch (Exception e) {
				CommonHelper.log("写入文件" + fileFullPath + "出错");
			}
		} else {
			CommonHelper.log("写入文件" + fileFullPath + "无权限");
		}
	}

	public static void writeSegmentFile(Context context, byte[] b,
			String fileFullPath, long fileFullLen) {
		// 获取扩展SD卡设备状态
		String sDStateString = android.os.Environment.getExternalStorageState();
		File myFile = null;
		// 拥有可读可写权限
		if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
			try {
				// 获取扩展存储设备的文件目录
				String fileDir = fileFullPath.substring(0,
						fileFullPath.lastIndexOf("/") + 1);
				File dir = new File(fileDir);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				boolean isAppend = false;
				myFile = new File(fileFullPath);
				if (myFile.exists()) {
					isAppend = true;
				} else {
					myFile.createNewFile();
				}
				if (myFile != null) {
					FileOutputStream outputStream = new FileOutputStream(
							myFile, isAppend);
					outputStream.write(b);
					outputStream.flush();
					outputStream.close();
					// xml存储完整文件大小
					writeFileSize(context, fileFullPath, fileFullLen);
				}
			} catch (Exception e) {
				CommonHelper.log("写入文件" + fileFullPath + "出错");
			}
		} else {
			CommonHelper.log("写入文件" + fileFullPath + "无权限");
		}
	}

	public static boolean writeFileSize(Context c, String key, long value) {
		SharedPreferences settings = c.getSharedPreferences("file",
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putLong(key, value);
		return editor.commit();
	}

	public static long readFileSize(Context c, String key) {
		SharedPreferences settings = c.getSharedPreferences("file",
				Context.MODE_PRIVATE);
		return settings.getLong(key, -1);
	}

	/**
	 * 删除所有文件，目录或者文件都适用，递归删除所有层级的文件或者文件夹
	 * 
	 * @param file
	 * @throws Exception
	 */
	public static void deleteAllFile(File file) throws Exception {
		if (file.exists()) {
			if (file.isFile()) {
				// 判断是否是文件
				file.delete();
			} else if (file.isDirectory()) {
				// 否则如果它是一个目录
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					// 遍历目录下所有的文件
					deleteAllFile(files[i]);
				}
			}
			file.delete();
		} else {
			throw new Exception("要删除的文件" + file + "不存在！");
		}
	}

	/**
	 * 根据图片路径读取字节流
	 * 
	 * @param filePath
	 *            文件路径
	 * @return
	 * @throws Exception
	 */
	public static byte[] getFileByte(String filePath) throws Exception {
		// 获取扩展SD卡设备状态
		String sDStateString = android.os.Environment.getExternalStorageState();
		File myFile = null;
		// 拥有可读可写权限
		if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
			try {
				// 打开文件
				myFile = new File(filePath);
				// 判断是否存在,不存在则创建
				if (!myFile.exists()) {
					throw new Exception("image file not found!");
				}
				long len = myFile.length();
				byte[] bytes = new byte[(int) len];

				BufferedInputStream bufferedInputStream = new BufferedInputStream(
						new FileInputStream(myFile));
				int r = bufferedInputStream.read(bytes);
				bufferedInputStream.close();
				if (r != len) {
					throw new IOException("error read image file");
				}
				return bytes;

			} catch (Exception e) {
				throw e;
			}
		} else {
			throw new Exception("没有读写权限");
		}
	}

	/**
	 * 获取文件夹下面的所以文件
	 * 
	 * @param directory
	 * @param lstFiles
	 */
	private static void getAllFiles(File directory, List<File> lstFiles) {
		File files[] = directory.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isDirectory()) {
					lstFiles.add(f);
					getAllFiles(f, lstFiles);
				} else {
					lstFiles.add(f);
				}
			}
		}
	}

	/**
	 * 加载图片，防止内存溢出
	 * 
	 * @param pathName
	 *            图片路径
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static Bitmap decodeSampledBitmapFromResource(String pathName,
			int reqWidth, int reqHeight) {
		// 获取尺寸
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, options);
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(pathName, options);
	}

	/**
	 * 计算图片变化后于原图的比例
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// 图像原始高度和宽度
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
		}
		return inSampleSize;
	}
}
